package com.sanpu.kxe.module.dialog;

import android.app.Dialog;
import android.content.Context;
import android.graphics.Bitmap;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.sanpu.kxe.R;
import com.sanpu.kxe.business.main.bean.InviteMakeMoneyOutput;
import com.sanpu.kxe.common.interfaces.UrlConstants;
import com.sanpu.kxe.common.utils.QRCode;
import com.sanpu.kxe.jump.imageloader.JKImageLoader;
import com.sanpu.kxe.jump.shareutil.ShareUtil;
import com.sanpu.kxe.jump.shareutil.share.ShareListener;
import com.sanpu.kxe.jump.shareutil.share.SharePlatform;
import com.sanpu.kxe.module.dialog.adapter.ShareEarningsAdapter;
import com.sanpu.kxe.module.widget.CenterScrollListener;
import com.sanpu.kxe.module.widget.OverFlyingLayoutManager;
import com.sanpu.kxe.utils.FileUtil;
import com.sanpu.kxe.utils.ScreenUtil;
import com.sanpu.kxe.utils.ToastUtil;
import com.sanpu.library.imagechoose.utils.PermissionsUtils;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.ButterKnife;

/**
 * Description：邀请赚钱
 * Created by 薛勇军 on 2019/9/26.
 */

public class ShareEarningsDialog implements View.OnClickListener {

    private ImageView closeIv;

    private RecyclerView bannerRv;

    private LinearLayout showLl;

    private FrameLayout shareViewFl;

    private ImageView  bigIv, qrcodeIv;

    private OverFlyingLayoutManager mOverFlyingLayoutManager;

    private Context mContext;

    private Dialog aDialog;

    private boolean canShare = false;

    private List<InviteMakeMoneyOutput> mInviteMakeMoneyOutputs = new ArrayList<>();

    public ShareEarningsDialog(Context context, List<InviteMakeMoneyOutput> inviteMakeMoneyOutputs) {
        this.mContext = context;
        this.mInviteMakeMoneyOutputs = inviteMakeMoneyOutputs;
        ShareEarningsDialog(context);
    }

    public void ShareEarningsDialog(Context context) {
        View inflate = LayoutInflater.from(context).inflate(R.layout.dialog_share_earnings_view, null);
        aDialog = new Dialog(context, R.style.bottom_pop_menu);
        closeIv = ButterKnife.findById(inflate, R.id.closeIv);
        bannerRv = ButterKnife.findById(inflate, R.id.bannerRv);

        ButterKnife.findById(inflate, R.id.shareWeChatLl).setOnClickListener(this);
        ButterKnife.findById(inflate, R.id.shareTimelineLl).setOnClickListener(this);
        ButterKnife.findById(inflate, R.id.saveSystemLl).setOnClickListener(this);

        View emptyView = ButterKnife.findById(inflate, R.id.emptyView);
        emptyView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                aDialog.dismiss();
            }
        });

        bigIv = ButterKnife.findById(inflate, R.id.bigIv);
        showLl = ButterKnife.findById(inflate, R.id.showLl);
        qrcodeIv = ButterKnife.findById(inflate, R.id.qrcodeIv);
        shareViewFl = ButterKnife.findById(inflate, R.id.shareViewFl);

        setUiBeforShow(context);

        aDialog.setContentView(inflate); // 把自定義view加上去
        aDialog.setCanceledOnTouchOutside(false);
        aDialog.setCancelable(false);
        aDialog.show();
    }

    public void setUiBeforShow(Context context) {
        closeIv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dismiss();
            }
        });
        mOverFlyingLayoutManager = new OverFlyingLayoutManager(1f, 0, 0, OverFlyingLayoutManager.HORIZONTAL);
        if (mInviteMakeMoneyOutputs !=null && mInviteMakeMoneyOutputs.size()>0) {
            bannerRv.setVisibility(View.VISIBLE);
            canShare = true;
            if (mInviteMakeMoneyOutputs.size()>1) {
                mOverFlyingLayoutManager.scrollToPosition(1);
                showShareBitmap(1);
            } else {
                showShareBitmap(0);
            }
        } else {
            bannerRv.setVisibility(View.INVISIBLE);
            canShare = false;
        }
        bannerRv.addOnScrollListener(new CenterScrollListener());
        bannerRv.setAdapter(new ShareEarningsAdapter(context, mInviteMakeMoneyOutputs));
        bannerRv.setLayoutManager(mOverFlyingLayoutManager);
        mOverFlyingLayoutManager.setOnPageChangeListener(new OverFlyingLayoutManager.OnPageChangeListener() {
            @Override
            public void onPageSelected(int position) {
                showShareBitmap(position);
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }

    public void dismiss() {
        if (aDialog != null && aDialog.isShowing()) {
            aDialog.dismiss();
        }
    }

    public void show() {
        if (aDialog != null && !aDialog.isShowing()) {
            aDialog.show();
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.shareWeChatLl:
                onShareWeChatClick();
                break;
            case R.id.shareTimelineLl:
                onShareTimelineClick();
                break;
            case R.id.saveSystemLl:
                onSaveSystemClick();
                break;
        }
    }

    /**
     * 分享到微信好友
     */
    public void onShareWeChatClick() {
        if (!canShare) return;
        shareViewFl.destroyDrawingCache();
        shareViewFl.setDrawingCacheEnabled(true);
        Bitmap mClipScreen = shareViewFl.getDrawingCache();
        if (mClipScreen == null) return;
        ShareListener shareListener = new ShareListener() {
            @Override
            public void shareSuccess() {
                ToastUtil.showTextViewPrompt("分享成功！");
            }

            @Override
            public void shareFailure(Exception e) {
                ToastUtil.showTextViewPrompt(e.getMessage());
            }

            @Override
            public void shareCancel() {
            }
        };
        ShareUtil.shareImage(mContext, SharePlatform.WX, mClipScreen, shareListener);
    }

    /**
     * 分享到微信朋友圈
     */
    public void onShareTimelineClick() {
        if (!canShare) return;
        shareViewFl.destroyDrawingCache();
        shareViewFl.setDrawingCacheEnabled(true);
        Bitmap mClipScreen = shareViewFl.getDrawingCache();
        if (mClipScreen == null) return;
        ShareListener shareListener = new ShareListener() {
            @Override
            public void shareSuccess() {
                ToastUtil.showTextViewPrompt("分享成功！");
            }

            @Override
            public void shareFailure(Exception e) {
                ToastUtil.showTextViewPrompt(e.getMessage());
            }

            @Override
            public void shareCancel() {
            }
        };
        ShareUtil.shareImage(mContext, SharePlatform.WX_TIMELINE, mClipScreen, shareListener);
    }

    /**
     * 保存到系统
     */
    public void onSaveSystemClick() {
        if (!canShare) return;
        shareViewFl.destroyDrawingCache();
        shareViewFl.setDrawingCacheEnabled(true);
        Bitmap mClipScreen = shareViewFl.getDrawingCache();
        if (mClipScreen == null) return;
        if (!PermissionsUtils.checkWriteStoragePermission(mContext))
            return;
        File result = FileUtil.saveShareImageToGallery(mContext, mClipScreen);
        ToastUtil.showTextViewPrompt(result != null ? "图片保存成功!请在相册查看" : "图片保存失败");
    }

    private void showShareBitmap(int position) {
        try {
            InviteMakeMoneyOutput output = mInviteMakeMoneyOutputs.get(position);
            if (output != null) {
                JKImageLoader.getInstance().displayImage(mContext,
                        UrlConstants.getBaseUrl() + output.getImagePath(), bigIv);
                if (!TextUtils.isEmpty(output.getInvitationLinkUrl())) {
                    showLl.setVisibility(View.VISIBLE);
                    String mCodeUrl = output.getInvitationLinkUrl();
                    Bitmap bitmap = QRCode.createQRCode(mCodeUrl, 500);
                    if (bitmap != null) {
                        qrcodeIv.setImageBitmap(QRCode.resizeImage(bitmap, ScreenUtil.dp2px(30), ScreenUtil.dp2px(30)));
                    }
                } else {
                    showLl.setVisibility(View.GONE);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
